<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    String wsPath = "ws://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
    <title>Home</title>
</head>
<body>
<h1>
    Hello world!  This is a WebSocket demo!
    <div id="message">

    </div>
</h1>

<script src="//apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script>
<script  src="//cdn.jsdelivr.net/sockjs/1/sockjs.min.js"></script>


<script type="text/javascript">

    $(function(){
        //建立socket连接
        var sock;
        if ('WebSocket' in window) {
            sock = new WebSocket("<%=wsPath%>ws");
        } else if ('MozWebSocket' in window) {
            sock = new MozWebSocket("<%=wsPath%>ws");
        } else {
            sock = new SockJS("<%=basePath%>ws");
        }
        sock.onopen = function (e) {
            console.log(e);
        };
        sock.onmessage = function (e) {
            console.log(e)
            $("#message").append("<p><font color='red'>"+e.data+"</font>")
        };
        sock.onerror = function (e) {
            console.log(e);
        };
        sock.onclose = function (e) {
            console.log(e);
        }
    });

</script>

</body>
</html>